#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef unsigned char BYTE;

void PSNR (BYTE *p1, BYTE *p2, int Size)
{
    double d;
    int i;
    d = 0;
    for (i = 0; i < Size; i++)
    {
        d += ((*p1) - (*p2)) * ((*p1) - (*p2));
        p1++;
        p2++;
    }
    printf ("Y: %5.2f, ", 10 * log10(255 * 255 / d * Size));

    d = 0;
    for (i = 0; i < Size/4; i++)
    {
        d += ((*p1) - (*p2)) * ((*p1) - (*p2));
        p1++;
        p2++;
    }
    printf ("U: %5.2f, ", 10 * log10(255 * 255 / d * Size / 4));

    d = 0;
    for (i = 0; i < Size/4; i++)
    {
        d += ((*p1) - (*p2)) * ((*p1) - (*p2));
        p1++;
        p2++;
    }
    printf ("V: %5.2f\n", 10 * log10(255 * 255 / d * Size / 4));

}

int main(int argc, char** argv)
{
    int frm;
    int H, W;
    BYTE *pBuf1, *pBuf2;
    FILE *fp1, *fp2;

    if (argc != 5)
    {
        printf ("PSNR [orginal] [decoded] [width] [height] \n");
        return 0;
    }

    W = atoi(argv[3]);
    H = atoi(argv[4]);

    frm = 0;
    fp1 = fopen (argv[1], "rb");
    fp2 = fopen (argv[2], "rb");
    if (NULL != fp1 && NULL != fp2)
    {
        pBuf1 = (BYTE*) malloc (H*W*3/2);
        pBuf2 = (BYTE*) malloc (H*W*3/2);
        while(0 != fread(pBuf1, 1, H*W*3/2, fp1) && 0 != fread(pBuf2, 1, H*W*3/2, fp2))
        {
            printf ("%4d: ", frm++);
            PSNR (pBuf1, pBuf2, H*W);
        }
        free (pBuf1);
        free (pBuf2);
    }
    else
    {
        printf ("Input File cannot open\n");
        return 0;
    }

    fclose (fp1);
    fclose (fp2);
}